import {
  pages
} from '~/tools/pages'
import {
  ui
} from '~/tools/ui'
import {
  dsx
} from '~/tools/datax'
import {
  numTool
} from '~/tools/num'
import {
  dateTool
} from '~/tools/date'
import {
  coupon as couponTool
} from '~/tools/coupon'
Page({
  data: {
    choice: {},
    initCouponPoints: 0,
    hasCoupon: true
  },
  onLoad(options) {
    const order = JSON.parse(options.order)
    order.coupon = order.coupon ?? {}
    const cp = typeof order.coupon.leftPoints != 'undefined' ? order.coupon.leftPoints : order.totalFee
    order.coupon.leftPoints = numTool.maxFixed(cp, 2)
    this.setData({
      order,
      user: JSON.parse(options.user),
      initCouponPoints: cp
    })
    this.gatherCoupons(order)
  },
  onReady() {

  },
  onShow() {

  },
  changeStepper(e) {
    const id = ui.eventData(e, 'id')
    const {
      choice
    } = this.data
    choice[id] = choice[id] || {}
    choice[id].num = e.detail.value
    this.setData({
      choice
    })
    this.calcLeftPoints(choice)
  },
  calcLeftPoints(choice) {
    const {
      order,
      couponList,
      initCouponPoints
    } = this.data
    let usedPoints = 0,
      minUnit = -1
    Object.keys(choice || {}).forEach(id => {
      const coupon = couponList.find(ele => ele._id == id)
      usedPoints += (coupon.unit * 1 * choice[id].num)
      minUnit = (minUnit < 0 ? coupon.unit * 1 : Math.min(coupon.unit * 1, minUnit))
    })
    // console.log(choice, usedPoints, order.coupon?.leftPoints)
    const leftPoints = initCouponPoints - usedPoints
    this.setData({
      'order.coupon.leftPoints': numTool.maxFixed(leftPoints, 2),
      hasCoupon: leftPoints > minUnit
    })
  },
  gatherCoupons(order) {
    const couponList = []
    order.goodsSnap.forEach(ele => {
      ele.couponList.forEach(c => couponList.push(c))
    })
    this.setData({
      couponList
    })
  },
  async getCouponTap() {
    const {
      order,
      couponList,
      choice,
      user,
      initCouponPoints,
      hasCoupon
    } = this.data

    const tnum = Object.values(choice).reduce((sum, v) => sum + v.num, 0)
    if (tnum <= 0) return await ui.confirmx('未选择优惠券或点数不足')

    const ok = await ui.confirmx(`${hasCoupon && '剩余点数可下次兑换。' || ''}确定兑换吗？`)
    if (!ok) return

    ui.loading()
    const results = [],
      that = this
    let getNum = 0,
      leftPoints = initCouponPoints * 1

    const ids = Object.keys(choice).filter(id => choice[id].num > 0)
    for (const id of ids) {
      const coupon = couponList.find(ele => ele._id == id)
      const num = choice[id].num * 1
      try {
        coupon._id = undefined
        couponTool.setupDuration(coupon)
        const res = await dsx.cloudUpdate('coupons', null, {
          ...coupon,
          userId: user._id,
          userName: user.personInfo?.nickName || '(昵称未设置)',
          amount: num,
          limit: num,
          left: num,
          orderId: order._id
        })
        results.push(res)
        if (res.result.errMsg.endsWith(":ok")) {
          getNum += num
          leftPoints -= (coupon.unit * num)
        }
        // console.log(id, res, leftPoints, getNum)
      } catch (err) {
        console.error(err)
      }
    } // for
    that.gotCoupons(getNum, leftPoints)
  },
  async gotCoupons(getNum, leftPoints) {
    if (!getNum) {
      ui.loading(false)
      return ui.toast(false, '领取失败')
    }

    try {
      const res = await dsx.cloudUpdate('orders', this.data.order._id, {
        'coupon.leftPoints': leftPoints
      })
    } catch (err) {
      console.error(err)
    }
    ui.loading(false)
    ui.toast(true, `已领取${getNum}张`, () => {
      pages.back(prePpage => {
        prePpage.onRefresh()
      })
    })
  },
  onBackTap() {
    pages.back()
  }
})